<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('translationImage.incomingInspection')"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('translationImage.checkoutInfo') }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialName')
							}}：</text>{{ data.iqcInfo.materialName }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('translationImage.supplierName')
							}}：</text>{{ data.iqcInfo.supplierName }}
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50" style="width: 100%;">
							<text class="item-info-title">{{ $t('distributedEnter.materialSpec')
								}}：</text>{{ data.iqcInfo.materialSpec }}
						</view>
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50">
							<text class="item-info-title">{{ $t('stockManage.materialUnit')
								}}：</text>{{ data.iqcInfo.unit }}
						</view>
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50">
							<text class="item-info-title">{{ $t('distributedEnter.materialCode')
								}}：</text>{{ data.iqcInfo.materialCode }}
						</view>
					</view>
				</view>

				<!--库位物料信息-->
				<view class="custom-form-card">
					<uni-collapse>
						<uni-collapse-item titleBorder="none" :show-animation="true" :open="false">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('taskList.inBarcode') }}
								</view>
							</template>
							<view class="custom-card-itemOne" v-for="(item, index) in data.inBarcode"
								:key="index">
								<text class="item-info-title">{{ $t('Common.barCode')
									}}：</text>{{ item.barcode }}
								<text class="item-info-title" style="margin-left:10rpx;">{{ $t('distributedOut.location')
									}}：</text>{{ item.targetLocationCode }}
								<!-- <text class="item-info-title" style="margin-left:20rpx;">{{ $t('distributedEnter.qty')
									}}：</text>{{ item.currentQty }} -->
								<!-- <button
									style="height: 40rpx;line-height: 40rpx;font-size: 12px;color: #fff;background-color: #3970E6"
									@click="detail(item.location_code)">{{ $t('finishInventory.view') }}</button> -->
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="element-auto">
					<view class="h-table gui-margin-top" style="background: #fff;">
						<view class="h-tr h-tr-3 h-thead ">
							<view class="h-td">{{ $t('translationImage.testItem') }}</view>
							<view class="h-td">{{ $t('distributedEnter.uom') }}</view>
							<view class="h-td">{{ $t('translationImage.standard') }}</view>
							<view class="h-td">{{ $t('translationImage.inspectionResult') }}</view>
							<view class="h-td">{{ $t('translationImage.supportingInfo') }}</view>
						</view>
						<view class="h-tr h-tr-3" v-for="(x, i) in data.testItem" :key="i"
							:class="{ 'passclass': data.qualifiedList[i] == 'pass' }, { 'failClass': data.qualifiedList[i] == 'fail' }">
							<view class="h-td">{{ x.checkProjectName }}</view>
							<view class="h-td">{{ x.unit }}</view>
							<view class="h-td">{{ x.standardItem }}</view>
							<view class="h-td">
								<view class="gui-flex gui-align-items-center" v-if="!data.isResult">
									<input v-if="x.resultType == 'text'" type="text"
										style="width: 120rpx;font-size: 14px;" v-model="x.checkResult">
									<input v-else-if="x.resultType == 'number'" type="number"
										style="width: 120rpx;font-size: 14px;" v-model="x.checkResult">
									<superweiCombox v-else-if="x.resultType == 'option'"
										style="text-align: right;width: 120rpx;padding:0"
										:candidates="data.selectedList" :placeholder="$t('translationImage.choose')"
										:isJSON="true" keyName="text" :defaultValue="data.objFilter[x.checkResult]"
										@select="selectFn($event, i)"></superweiCombox>
								</view>
								<view class="gui-flex gui-align-items-center" v-else>
									{{ x.checkResult == 'pass' ? $t('translationImage.qualified') :
										(x.checkResult == 'fail' ? $t('translationImage.qualifiedNo') : x.checkResult) }}
								</view>
							</view>
							<view class="h-td">
								<view class="custom-td-operate" @click="rowClick(i)">
									{{ $t('translationImage.operation') }}
								</view>
							</view>
						</view>
					</view>
					<view class="iqc-res" v-if="!data.isResult">
						{{ $t('translationImage.conclusion') }}：{{ totalQualified }}
					</view>
				</view>

				<!-- 底部操作栏 -->
				<view class="page-bottom-box" v-if="!data.isResult">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
						{{ $t('calendar.submit') }}
					</view>
				</view>
			</view>
			<!-- 页面弹窗  检查项 操作 上传图片-->
			<uni-popup ref="inputDialog" type="center">
				<view class="input-dialog-box">
					<view class="input-dialog-content">
						<uni-section :title="$t('translationImage.selectImg')" type="line">
							<view class="example-body">
								<uni-file-picker :auto-upload='false' @select="select" v-model="data.uploadImg"
									:readonly="data.isResult"></uni-file-picker>
								<view style="line-height: 30px;" v-if="!data.uploadImg.length && data.isResult">
									{{ $t('translationImage.notAvailableImg') }}
								</view>
							</view>
						</uni-section>
					</view>
					<view class="input-dialog-footer" v-if="!data.isResult">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('calendar.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('calendar.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>


			<!--页面弹窗展示物料详情-->
			<uni-popup ref="detailDialog" type="center">
				<view class="input-dialog-box">
					<scroll-view scroll-y="true" :style="{ height: data.height + 'rpx' }">
						<view class="custom-form-card">
							<uni-collapse>
								<uni-collapse-item titleBorder="none" :show-animation="true" :open="true"
									v-for="(item, index) in data.detailArr" :key="index">
									<template v-slot:title>
										<view class="custom-card-title">
											<text class="title-line"></text>
											{{ item.location_code }}
										</view>
									</template>
									<view class="custom-card-itemOne" style="margin-top: 3rpx;">
										<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
											}}：</text>{{ item.barcode }}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{ $t('distributedEnter.materialCode')
											}}：</text>{{ item.material_code }}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{ $t('distributedEnter.materialName')
											}}：</text>{{ item.material_name }}
									</view>
									<view class="custom-card-itemOne">
										<text class="item-info-title">{{ $t('distributedEnter.qty')
											}}：</text>{{ item.current_qty }}
									</view>
								</uni-collapse-item>

							</uni-collapse>
						</view>

					</scroll-view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelDetail()">
							{{ $t('calendar.cancel') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { TEST_URL, PROD_URL, IMG_BASE_URL } from '@/constant/config.js'
import { navigateBack } from '@/utils/routerSkip.js';
import { reactive, ref, onMounted, computed, toRaw, watchEffect } from 'vue';
import { findRelationByCode, insertIqcCheck, getLibraryNumber, getfindLocationByCode } from '@/api/api.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT } from '@/constant/index.js'
import { useStore } from "vuex";
import { TOKEN } from '@/constant/index.js';
import { getDataDictionaryFn } from '@/utils/index.js'
import superweiCombox from '@/components/superweiCombox';
//JS国际化引入
import { useI18n } from 'vue-i18n';

components: {
	superweiCombox
}
const { t } = useI18n();

const props = defineProps({
	materialCode:String
})
let store = useStore();
let popup = ref(null)
let inputDialog = ref(null)
let detailDialog = ref(null)

let data = reactive({
	testItem: [], //检测数据集合
	uploadImg: [],
	selectedList: [{
		text: t('translationImage.qualified'),
		value: 'pass'
	}, {
		text: t('translationImage.qualifiedNo'),
		value: 'fail'
	},],
	imgIndex: 0, //用户当前点击行数索引
	qualifiedList: [], //每一项的检验结果集合
	isPassImgRequired: false, //判断合格是否必须上传图片
	isFailImgRequired: false, //判断不合格是否必须上传图片
	isResult: false, //判断是否有结果
	objFilter: {
		pass: t('translationImage.qualified'),
		fail: t('translationImage.qualifiedNo'),
	},
	locationDataArr: [], // 库位维度的物料汇总
	detailArr: [], //物料明细
	height: 800,
	inBarcode:[]
})

//页面标题高度
const navHeight = computed(() => {
	return store.state.navHeight
})

onMounted(() => {
	findRelationByCodeFn()
	getInitData()
	getlocationDataArr()
	barcodeList()
	setTimeout(() => {
		// console.log(data.iqcInfo)
	}, 3000)
})

data.iqcInfo = computed(() => {
	return store.state.iqcInfo
})

const barcodeList = () => {
	getfindLocationByCode({
		relationItemCode: props.materialCode,
		instockCode: data.iqcInfo.instockCode,
		checkType: 'IQC'
	}).then(res => {
		console.log('12222-res.data',res.data)
		data.inBarcode=res.data
	})
}

// 判断所有数据是否合格
const totalQualified = computed(() => {
	if (data.testItem.length == 0) return '';
	let isTrue = data.qualifiedList.every(x => {
		return x === 'pass'
	})
	let isFail = data.qualifiedList.some(x => {
		return x === 'fail'
	})
	if (isTrue) {
		return t('translationImage.qualified')
	} else if (isFail) {
		return t('translationImage.qualifiedNo')
	} else {
		return ''
	}
})

// 算出表格每行合格量和总合格数
watchEffect(() => {
	console.log(data.testItem)
	//pass 合格 ; fail 不合格
	data.testItem.forEach((x, i) => {
		console.log(x.checkResult, i, 'watchEffect')
		if (x.checkResult) {
			switch (x.resultType) {
				case 'text':
					//如果是文字类型，不做判断，默认合格
					data.qualifiedList[i] = 'pass'
					break;
				case 'number':
					//如果是数值类型，判断是否在合格区间
					let a = x.standardItem.split('~')
					let b = Number(a[0])
					let c = Number(a[1])
					let d = Number(x.checkResult)
					if (!isNaN(d) && d >= b && d <= c) {
						data.qualifiedList[i] = 'pass'
					} else {
						data.qualifiedList[i] = 'fail'
					}
					break;
				case 'option':
					data.qualifiedList[i] = x.checkResult
					break;
				default:
					break;
			}
		} else {
			data.qualifiedList[i] = ''
		}
	})
})


//获取库位明细
const getlocationDataArr = () => {
	var obj = {}
	obj.sourceCode = data.iqcInfo.instockCode
	obj.materialCode = props.materialCode
	data.locationDataArr = []
	getLibraryNumber(obj).then(res => {
		if (res.code == 0) {
			data.locationDataArr = res.data
		}
	})
}
const getInitData = async () => {
	// 控制PDA质检画面的佐证资料是否需要上传照片
	let info = await getDataDictionaryFn('SupportingInformation')
	info.data.forEach(x => {
		if (x.value === 'pass') {
			data.isPassImgRequired = x.selected
		} else if (x.value === 'fail') {
			data.isFailImgRequired = x.selected
		}
	})
	// console.log(data, 'getInitData')
}

//提交数据
const submit = () => {
	if (data.testItem.length == 0) {
		uni.showToast({
			title: t('JsInternational.plsMaintain'),
			icon: 'none'
		})
		return
	};
	// 检测每行检测结果是否填写
	let isTrue = data.testItem.every(x => {
		return x.checkResult
	})
	console.log(isTrue)
	if (!isTrue) {
		uni.showToast({
			title: t('JsInternational.plsFillAll'),
			icon: 'none'
		})
		return
	}
	// 检测合格结果佐证资料是否必填
	if (!data.isPassImgRequired) {
		if (!data.testItem.every(x => x.imgList.length)) return uni.showToast({
			title: t('materials.pleaseUploadSupporting'),
			icon: 'none'
		})
	}
	// 检测不合格结果佐证资料是否必填
	if (!data.isFailImgRequired) {
		if (!data.testItem.every(x => x.imgList.length)) return uni.showToast({
			title: t('materials.pleaseUploadSupportingInfo'),
			icon: 'none'
		})
	}
	data.testItem.forEach(x => {
		let arry = x.imgList.map(x => x.url)
		console.log(arry)
		x.supportImage = arry.join()
	})
	console.log(data.testItem)
	let param = {
		// isCheck:totalQualified == '合格' ? '1' : '0' ,
		k3Id: data.iqcInfo.k3Id,
		instockTime: data.iqcInfo.instockTime,
		instockCode: data.iqcInfo.instockCode,
		materialCode: data.iqcInfo.materialCode,
		materialName: data.iqcInfo.materialName,
		materialSpec: data.iqcInfo.materialSpec,
		qty: data.iqcInfo.qty,
		unit: data.iqcInfo.unit,
		qmsRelationDS: toRaw(data.testItem)
	}
	console.log(param)
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	insertIqcCheck(param).then(res => {
		try {
			let inputParameter = JSON.stringify(param)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '来料检验'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code, //返回状态
				errorMessage: res.msg, //错误信息
				isPass: res.code == 0 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		console.log(res, 'paramparamparam')
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				complete: () => {
					setTimeout(() => {
						navigateBack({
							delta: 1
						})
					}, 1000)
				}
			})
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}
// 上传图片获取开始上传
const select = (e) => {
	const tempFilePaths = e.tempFilePaths;
	let isDev = process.env.NODE_ENV === 'development';
	let baseUrl = isDev ? TEST_URL : PROD_URL
	
	let token = uni.getStorageSync(TOKEN);
	let formData = {
		id: data.iqcInfo.instockCode,
		type: 'qms_iqc_check_h',
		status: 0
	}
	uni.showLoading({
		title: t('JsInternational.uploading')
	});
	for (var i in tempFilePaths) { //多文件
		uni.uploadFile({
			url: baseUrl+ '/api2/eletile-digital/sys-minio/upload', //上传接口
			name: 'file',
			header: {
				// 'Access-Control-Allow-Origin': '*',
				// "content-type": "multipart/form-data",
				'Authorization': 'Bearer ' + token
			},
			filePath: tempFilePaths[i],
			formData: formData,
			success: (uploadFileRes) => {
				uni.hideLoading();
				console.log('uploadFileRes', uploadFileRes)
				const back = uploadFileRes;
				console.log(back)
				if (back.statusCode == 200) {
					let imgPath = baseUrl+'/api2/img/platform' + back.data;
					data.uploadImg.push({
						name: '',
						extname: 'png',
						url: imgPath
					})
					console.log(data.uploadImg);
				} else {
					console.log(back.errMsg)
					uni.showToast({
						title: back.errMsg,
						icon: "none"
					});
				}
			},
			fail: () => {
				uni.hideLoading();
				uni.showToast(t('JsInternational.pictureUploading'))
			},
			complete: function () {
				uni.hideLoading();
			}
		});
	}
}
// 获取物料检测项
const findRelationByCodeFn = () => {
	findRelationByCode({
		relationItemCode: props.materialCode,
		instockCode: data.iqcInfo.instockCode,
		checkType: 'IQC'
	}).then(res => {
		if (res.code == 0) {
			data.isResult = res.data.length > 0 && res.data[0].checkResult != null
			data.testItem = res.data;
			data.qualifiedList = []
			data.testItem.forEach(x => {
				x.imgList = []
				data.qualifiedList.push('')
				if (x.supportImage) {
					x.imgList = x.supportImage.split(',').map(x => {
						return {
							name: '',
							extname: 'png',
							url: x
						}
					})
				}
			})
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	})
}
// 下拉列表选择
const selectFn = (e, index) => {
	data.testItem[index].checkResult = e.value
	console.log(e, index)
}
// 表格点击操作
const rowClick = (index) => {
	data.imgIndex = index;
	data.uploadImg = data.testItem[index].imgList;
	console.log(data.uploadImg, 'data.uploadImg');
	inputDialog.value.open();
}
const cancelFn = () => {
	inputDialog.value.close();
	data.uploadImg = []
}
const confirmFn = () => {
	data.testItem[data.imgIndex].imgList = data.uploadImg
	inputDialog.value.close();
}

//点击查看按钮
const detail = (locationCode) => {
	var obj = {}
	data.detailArr = []
	obj.sourceCode = data.iqcInfo.instockCode
	obj.materialCode = props.materialCode
	obj.locationCode = locationCode
	// getLibraryDetails(obj).then((res) => {
	// 	if (res.status == 200) {
	// 		data.detailArr = res.data
	// 	}
	// })
	detailDialog.value.open()
}

//取消
const cancelDetail = () => {
	detailDialog.value.close()
}
</script>

<style scoped lang="scss">
.iqc-res {
	text-align: right;
	font-size: 32rpx;
	padding: 30rpx;
}

.custom-td-operate {
	display: inline-block;
	padding: 10rpx 20rpx;
	border-radius: 8rpx;
	background: #3970E6;
	color: #fff;
	line-height: 28rpx;
}
</style>